package org.koyad.portal.portalPage.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.koyad.portal.annotations.Action;
import org.koyad.portal.annotations.Action.Forward;
import org.koyad.portal.api.BaseAction;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.utils.FileUtils;
import org.koyad.portal.utils.LogUtils;

@Action(
	name = "editPageLayout",
	forwards = { 
					@Forward(name = "success", path = "/jsp/success.jsp"),
					@Forward(name = "failure", path = "/jsp/failure.jsp")
			   }
)
public class EditPageLayoutAction  extends BaseAction {

	private static final LogUtils LOGGER = LogUtils.getLogger(EditPageLayoutAction.class);
	
	@Override
	public void execute() {
		
		LOGGER.startMethod("execute");
		
		HttpServletRequest req = PistonContext.getContext().getRequest();
		String pageId = getQueryStringParameter(req.getQueryString(), "piston_edit_page_id");
		
		String pageContent = "";
		if(null != pageId) {
			try {
				InputStream is = new FileInputStream(new File("D:/Tools/piston-pages/external/" + pageId + ".xml"));
				pageContent = FileUtils.readFileAsString(is);
			} catch (FileNotFoundException e) {
				LOGGER.logException(e);
			}
		} else {
			StringBuffer buffer = new StringBuffer();
			buffer.append("<div class=\"row\">");
			buffer.append("<div class=\"tileContainer\" oncontextmenu=\"return showContextMenu(event);\"  ondragover=\"dragOver(event)\" ondrop=\"drop(event)\">");
			buffer.append("</div></div>");
			pageContent = buffer.toString();
		}
		
		LOGGER.info("Page content : " + pageContent);
		PistonContext.getContext().getRequest().setAttribute("pageContent", pageContent);
		
		createView("/_portalPage/xml/pageBuilder.xml");
		
		LOGGER.endMethod("execute");
	}
	
	private String getQueryStringParameter(String queryString, String parameter) {
		if(null != queryString) {
			StringTokenizer tokenizer = new StringTokenizer(queryString, "&");
			while(tokenizer.hasMoreTokens()) {
				String token = tokenizer.nextToken();
				if(token.startsWith(parameter)) {
					return token.substring(token.indexOf('=') + 1);
				}
			}
		}
		return null;
	}

}
